package com.runshu.runshuwulian.base;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public abstract class BaseFragment extends Fragment {
    private Unbinder unbinder;
    protected Context context;
    protected String TAG;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate( setLayoutId(), container, false );
        unbinder = ButterKnife.bind( this, view );
        context = getActivity();
        TAG = getActivity().getLocalClassName();
        initView();


        if (useEventBus()) {
            EventBus.getDefault().register( this );
        }

        return view;
    }

    protected boolean useEventBus() {
        return false;
    }

    public BaseActivity selfAct() {
        if (getActivity() instanceof BaseActivity)
            return (BaseActivity) getActivity();
        return null;
    }

    protected abstract int setLayoutId();

    protected void initView() {
    }

    public void showShortToast(String str) {
        selfAct().showShortToast( str );
    }

    public RequestBody getRequestBody(JSONObject jsonObject) {
        return RequestBody.create( MediaType.parse( "application/json; charset=utf-8" ), jsonObject.toString() );
    }


    public void startActivityByDefaultAnim(Class activity) {
        ((BaseActivity) selfAct()).startActivityByDefaultAnim( activity );
    }

    public void startActivityByDefaultAnim(Intent intent) {
        selfAct().startActivityByDefaultAnim( intent );
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister( this );
    }
}
